<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    :before-close="handleClose"
    @open="handleDialogOpen"
  >
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <!-- 检测项编码 -->
      <el-form-item label="检测项编码：" prop="index_code" required>
        <el-row :gutter="10">
          <el-col :span="18">
            <el-input
              v-model="formData.index_code"
              placeholder="请输入检测项编码"
              clearable
              :disabled="isEditMode || isSystemCode"
              :class="{'disabled-input': isEditMode || isSystemCode}"
              maxlength="64"
            />
          </el-col>
          <el-col :span="6" v-if="!isEditMode">
            <el-switch
              v-model="isSystemCode"
              active-text="系统编号"
              inactive-text=""
              style="margin-top: 13px;"
              @change="handleSystemCodeChange"
            ></el-switch>
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 检测项名称 -->
      <el-form-item label="检测项名称：" prop="index_name" required>
        <el-input
          v-model="formData.index_name"
          placeholder="请输入检测项名称"
          clearable
          maxlength="255"
        />
      </el-form-item>

      <!-- 检测项类型 -->
      <el-form-item label="检测项类型：" prop="index_type" required>
        <el-select
          v-model="formData.index_type"
          placeholder="请选择检测项类型"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in indexTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 检测工具 -->
      <el-form-item label="检测工具：" prop="qc_tool">
        <el-input
          v-model="formData.qc_tool"
          placeholder="请输入检测工具"
          clearable
          maxlength="255"
        />
      </el-form-item>

      <!-- 检测值类型 -->
      <el-form-item label="检测值类型：" prop="qc_result_type" required>
        <el-select
          v-model="formData.qc_result_type"
          placeholder="请选择检测值类型"
          style="width: 100%"
          @change="handleResultTypeChange"
        >
          <el-option
            v-for="item in resultTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 值属性/检测单位 -->
      <el-form-item label="值属性：" prop="qc_result_spc">
        <el-select
          v-model="formData.qc_result_spc"
          :placeholder="unitPlaceholder"
          style="width: 100%"
          :disabled="!formData.qc_result_type"
          filterable
          allow-create
          maxlength="255"
        >
          <el-option
            v-for="unit in currentUnitOptions"
            :key="unit"
            :label="unit"
            :value="unit"
          />
        </el-select>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注：" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息（可选）"
          clearable
          maxlength="500"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">
        {{ isEditMode ? '保存修改' : '确 定' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers.js"

// 检测值类型映射（字符 -> 文字）
const RESULT_TYPE_MAP = {
  '1': '数值型',
  '2': '布尔型',
  '3': '文本型'
};

// 单位映射表（字符类型 -> 单位数组）
const UNIT_MAPPING = {
  '1': ['mm', 'cm', 'm', 'inch', 'g', 'kg', 'mg', '°C', '°F', 'Pa', 'kPa', 's', 'min', 'h', 'A', 'mA', 'V', 'mV', 'Ω', 'kΩ', 'MΩ'],
  '2': ['是/否', '合格/不合格', '通过/不通过', '有/无', '真/假'],
  '3': ['文本', '字符串', '描述', '说明']
};

// 检测项类型映射（字符 -> 文字）
const INDEX_TYPE_MAP = {
  '1': '尺寸',
  '2': '物理性能检测',
  '3': '外观',
  '4': '化学成分检测',
  '5': '环境与耐久性测试',
  '6': '工艺性能测试',
  '7': '无损检测'
};

export default {
  name: 'IndexDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    formData: {
      type: Object,
      default: () => ({
        index_id: null,
        index_code: '',
        index_name: '',
        index_type: '',
        qc_tool: '',
        qc_result_type: '',
        qc_result_spc: '',
        remark: '',
        attr1: '',
        attr2: '',
        attr3: 0,
        attr4: 0,
        create_by: '',
        create_time: '',
        update_by: '',
        update_time: '',
        is_delete: '0'
      })
    },
    isEditMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      loading: false,
      codeLoading: false, // 控制自动生成编码按钮的加载状态
      isSystemCode: true, // 是否使用系统编号
      // 检测项类型选项（字符值对应文字显示）
      indexTypeOptions: Object.entries(INDEX_TYPE_MAP).map(([value, label]) => ({
        value: value.toString(),
        label
      })),
      // 检测值类型选项（字符值对应文字显示）
      resultTypeOptions: Object.entries(RESULT_TYPE_MAP).map(([value, label]) => ({
        value: value.toString(),
        label
      })),
      rules: {
        index_code: [
          { required: true, message: '请输入检测项编码', trigger: 'blur' },
          { max: 64, message: '长度不能超过64个字符', trigger: 'blur' }
        ],
        index_name: [
          { required: true, message: '请输入检测项名称', trigger: 'blur' },
          { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
        ],
        index_type: [
          { required: true, message: '请选择检测项类型', trigger: 'change' }
        ],
        qc_tool: [
          { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
        ],
        qc_result_type: [
          { required: true, message: '请选择检测值类型', trigger: 'change' }
        ],
        qc_result_spc: [
          {
            validator: (rule, value, callback) => {
              if (this.formData.qc_result_type && !value) {
                callback(new Error('请选择或输入值属性'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          },
          { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    currentUnitOptions() {
      if (!this.formData.qc_result_type) return [];
      return UNIT_MAPPING[this.formData.qc_result_type] || [];
    },
    unitPlaceholder() {
      if (!this.formData.qc_result_type) return '请先选择检测值类型';
      return this.currentUnitOptions.length > 0
        ? '请选择或输入值属性'
        : '请输入值属性';
    }
  },
  created() {
    // 初始化时如果是系统编号，则生成编号
    if (this.isSystemCode) {
      this.generateAutoCode();
    }
  },
  methods: {
    // 处理系统编号开关变化
    handleSystemCodeChange(val) {
      if (val) {
        // 如果开启系统编号，则生成编号
        this.generateAutoCode();
      } else {
        // 如果关闭系统编号，则清空编号
        this.formData.index_code = '';
      }
      
      // 使用nextTick确保DOM更新后触发校验
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField('index_code');
        }
      });
    },

    // 生成自动编码
    generateAutoCode() {
      if (!this.isSystemCode) {
        this.formData.index_code = '';
        return;
      }
      this.codeLoading = true;
      getAutoNumbers(7).then(response => {
        if (response.code === 200) {
          this.formData.index_code = response.msg;
          // 清除index_code字段的验证提示
          if (this.$refs.form) {
            this.$refs.form.validateField('index_code');
          }
        } else {
          this.$message.error('获取编号失败');
        }
        this.codeLoading = false;
      }).catch(() => {
        this.$message.error('获取编号失败');
        this.codeLoading = false;
      });
    },

    handleDialogOpen() {
      this.resetFormValidation();

      // 编辑模式下确保数据格式正确
      if (this.isEditMode) {
        // 确保index_type是字符串
        if (this.formData.index_type !== null && this.formData.index_type !== undefined) {
          this.formData.index_type = this.formData.index_type.toString();
        }

        // 确保qc_result_type是字符串
        if (this.formData.qc_result_type !== null && this.formData.qc_result_type !== undefined) {
          this.formData.qc_result_type = this.formData.qc_result_type.toString();
        }
      }
    },

    getIndexTypeName(value) {
      return INDEX_TYPE_MAP[value] || value;
    },

    getResultTypeName(value) {
      return RESULT_TYPE_MAP[value] || value;
    },

    handleResultTypeChange() {
      this.formData.qc_result_spc = '';
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField('qc_result_spc');
        }
      });
    },

    resetFormValidation() {
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },

    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          this.$message.error('请填写完整必填信息');
          return;
        }

        this.loading = true;
        
        // 如果是新增模式且启用系统编号，获取最终编号并消费流水号
        if (!this.isEditMode && this.isSystemCode) {
          try {
            // 使用getAutoNumbersConsume消费流水号
            const response = await getAutoNumbersConsume(7);
            if (response && response.code === 200) {
              this.formData.index_code = response.msg;
            } else {
              this.$message.error('获取编号失败，请重试');
              this.loading = false;
              return;
            }
          } catch (error) {
            this.$message.error('获取最终编号失败，请重试');
            this.loading = false;
            return;
          }
        }
        
        try {

          const payload = {
            index_id: this.formData.index_id,
            index_code: this.formData.index_code,
            index_name: this.formData.index_name,
            index_type: this.formData.index_type,
            qc_tool: this.formData.qc_tool || '',
            qc_result_type: this.formData.qc_result_type,
            qc_result_spc: this.formData.qc_result_spc || '',
            remark: this.formData.remark || '',
            attr1: this.formData.attr1 || '',
            attr2: this.formData.attr2 || '',
            attr3: this.formData.attr3 || 0,
            attr4: this.formData.attr4 || 0,
            is_delete: this.formData.is_delete || '0'
          };

          if (this.isEditMode) {
            payload.update_by = 'system';
            payload.update_time = new Date().toISOString();
          } else {
            payload.create_by = 'system';
            payload.create_time = new Date().toISOString();
          }

          const url = `/ldzl-qc/qc/qcIndex/${this.isEditMode ? 'updateQcIndex' : 'insertQcIndex'}`;

          await request({
            url: url,
            method: 'post',
            data: payload
          });

          this.$message.success(this.isEditMode ? '修改成功' : '添加成功');
          this.$emit('submit-success');
          this.$emit('update:visible', false);
        } catch (error) {
          console.error('操作失败:', error);
          this.$message.error(error.response?.data?.message || '操作失败');
        } finally {
          this.loading = false;
        }
      });
    },

    cancel() {
      this.resetFormValidation();
      this.$emit('update:visible', false);
    },

    handleClose(done) {
      if (this.isFormChanged()) {
        this.$confirm('未保存的数据将丢失，确定关闭吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.cancel();
          done();
        }).catch(() => {});
      } else {
        this.cancel();
        done();
      }
    },

    isFormChanged() {
      const initialData = {
        index_code: '',
        index_name: '',
        index_type: '',
        qc_tool: '',
        qc_result_type: '',
        qc_result_spc: '',
        remark: ''
      };
      return Object.keys(initialData).some(
        key => this.formData[key] !== initialData[key]
      );
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (val && !this.isEditMode && this.isSystemCode) {
        this.$nextTick(() => {
          this.generateAutoCode();
        });
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
  padding: 20px 20px 0;
  border-top: 1px solid #e8eaec;
}

/* 新增样式 */
.disabled-input .el-input__inner {
  color: #c0c4cc; /* 禁用状态下的文字颜色 */
  background-color: #f5f7fa; /* 禁用状态下的背景颜色 */
  cursor: not-allowed; /* 禁用状态下的鼠标样式 */
}

.disabled-input .el-input__inner:hover {
  border-color: #dcdfe6; /* 禁用状态下的边框颜色 */
}
</style>
